//
//  MTLoadingDataPlugin.swift
//  MT
//
//  Created by zhang qiang on 2018/12/2.
//  Copyright © 2019年 张强. All rights reserved.
//

import Foundation
import UIKit
import Moya
import Result

public class MTLoadingDataPlugin : PluginType {
    
    let viewController : UIViewController!
    
    public init(viewController : UIViewController){
        if viewController is RefreshView {
            Dlog("实现了")
        }
        self.viewController = viewController
    }
    
    /// Called immediately before a request is sent over the network (or stubbed).
    public func willSend(_ request: RequestType, target: TargetType){
        //DispatchQueue.main.sync {
            viewController.startLoading()
//        }
    }
    
    /// Called after a response has been received, but before the MoyaProvider has invoked its completion handler.
    public func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType){
        
        switch result {
        case let .success(response):
            do{
                let data = try response.mapResponseOriginalData(type: Dictionary<String, AnyClass>.self)
                if let d = data{
                    if d.code == nil || RequestSuccessCodes.contains(d.code!){
                        viewController.loadDataSuccess()
                    }else{
                        viewController.loadDataFailed(reason: .network)//server
                    }
                    
                }else{
                    viewController.loadDataFailed(reason: .network)//server
                }
            }catch{
                viewController.loadDataFailed(reason: .network)//server
            }
            
        case let.failure(error):
            
            switch error{
            case .underlying(_, _):
                viewController.loadDataFailed(reason: .network)
            default :
                viewController.loadDataFailed(reason: .network)//server
            }
            
        }
        
    }
    
    /// Called to modify a result before completion
}



//public class HudLoadingPlugin : PluginType {
//    
//    let viewController : UIViewController!
//    
//    public init(viewController : UIViewController){
//        self.viewController = viewController
//    }
//    
//    /// Called immediately before a request is sent over the network (or stubbed).
//    public func willSend(_ request: RequestType, target: TargetType){
//        viewController.showHudLoadingView()
//    }
//    
//    /// Called after a response has been received, but before the MoyaProvider has invoked its completion handler.
//    public func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType){
//        viewController.hideHudLoadingView()
//    }
//    
//}
